package site.tuluan.sp4j.module.sys.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import site.tuluan.sp4j.common.core.controller.BaseController;
import site.tuluan.sp4j.common.core.domain.AjaxResult;
import site.tuluan.sp4j.common.core.domain.entity.SysUserEntity;
import site.tuluan.sp4j.common.utils.StringUtils;
import site.tuluan.sp4j.common.utils.security.SecurityUtils;
import site.tuluan.sp4j.module.sys.controller.vo.PasswordVo;
import site.tuluan.sp4j.module.sys.controller.vo.SysUserVo;
import site.tuluan.sp4j.module.sys.service.ISysUserService;

import javax.annotation.Resource;

@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Resource
    private ISysUserService userService;

    /**
     * 用户新增
     */
    @RequiresPermissions("system:user:add")
    @PostMapping("/add")
    public AjaxResult register(SysUserVo userVo) {
        SysUserEntity userEntity = userVo.trans2SysUserEntity();
        userEntity.setSalt(SecurityUtils.randomSalt());
        userEntity.setPassword(userService.calcEncryptedPassword(userEntity.getPassword(), userEntity.getSalt()));
        userEntity.preInsert();
        userService.save(userEntity);
        return AjaxResult.buildSuccessResult();
    }

    /**
     * 用户更新
     */
    @RequiresPermissions("system:user:edit")
    @PutMapping()
    public AjaxResult update(SysUserVo userVo) {
        if (StringUtils.isEmpty(userVo.getId())) {
            return AjaxResult.buildFailureResult(300, "无用户ID信息");
        }
        SysUserEntity existUser = userService.getById(userVo.getId());
        userVo.trans2SysUserEntity(existUser);
        existUser.preUpdate();

        userService.updateById(existUser);
        return AjaxResult.buildSuccessResult();
    }

    /**
     * 用户删除
     */
    @RequiresPermissions("system:user:remove")
    @DeleteMapping("/{userId}")
    public AjaxResult remove(@PathVariable String userId) {
        userService.removeById(userId);
        return AjaxResult.buildSuccessResult();
    }

    /**
     * 查询
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    public AjaxResult list(@RequestParam(value = "id", required = false) String id,
                           @RequestParam(value = "account", required = false) String account,
                           @RequestParam(value = "nickName", required = false) String nickName,
                           @RequestParam(value = "phone", required = false) String phone,
                           @RequestParam(value = "sex", required = false) String sex,
                           @RequestParam(value = "current", required = false) Long current,
                           @RequestParam(value = "size", required = false) Long size) {
        if (current == null || size == null) {
            current = 1L;
            size = 10L;
        }

        IPage<SysUserEntity> userList = userService.lambdaQuery()
                .eq(StringUtils.isNotEmpty(id), SysUserEntity::getId, id)
                .like(StringUtils.isNotEmpty(account), SysUserEntity::getAccount, account)
                .like(StringUtils.isNotEmpty(nickName), SysUserEntity::getNickName, nickName)
                .like(StringUtils.isNotEmpty(phone), SysUserEntity::getPhone, phone)
                .eq(StringUtils.isNotEmpty(sex), SysUserEntity::getSex, sex)
                .page(new Page<>(current, size));

        return AjaxResult.buildSuccessResult(userList);
    }

    /**
     * 密码重置
     */
    @RequiresPermissions("system:user:resetPwd")
    @PutMapping("/resetPassword")
    public AjaxResult resetPassword(@RequestBody PasswordVo passwordVo) {
        SysUserEntity userEntity = userService.getById(passwordVo.getId());

        if (userEntity == null) {
            return AjaxResult.buildFailureResult(300, "无此用户");
        }

        boolean result;
        try {
            userEntity.setPassword(passwordVo.getPassword());
            userEntity.preUpdate();
            result = userService.resetPassword(userEntity);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return AjaxResult.buildFailureResult(300, e.getMessage());
        }

        return result ? AjaxResult.buildSuccessResult() : AjaxResult.buildFailureResult();
    }
}
